package com.binhanh.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.binhanh.common.constant.Constants;

/**
 * kết nối, lấy dữ liệu từ server và xử lý timeout
 * 
 * @author lunnd
 * 
 */

public class ServiceUtils {
	public static final int CONTENT_TYPE_TEXT = 0;
	public static final int CONTENT_TYPE_JSON = 1;

	public ServiceUtils() {

	}

	/**
	 * Lấy dữ liệu từ server bằng cách truyền url
	 * 
	 * @param strUrl
	 * @return
	 * @throws IOException
	 */
	public static String getServiceByGet(String strUrl) throws Exception {
		String data = "";
		InputStream iStream = null;
		HttpURLConnection urlConnection = null;

		URL url = new URL(strUrl);
		// Creating an http connection to communicate with url
		urlConnection = (HttpURLConnection) url.openConnection();

		// Thiết lập timeout
		urlConnection.setConnectTimeout(Constants.TIMEOUT_WAITING);
		urlConnection.setReadTimeout(Constants.TIMEOUT_WAITING);

		// Kết nối đến tài nguyên
		urlConnection.connect();

		// lấy mã kết quả
		int responseCode = urlConnection.getResponseCode();

		if (responseCode == HttpURLConnection.HTTP_OK) {
			// Reading data from url
			iStream = urlConnection.getInputStream();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					iStream));

			StringBuffer sb = new StringBuffer();

			String line = "";
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}

			data = sb.toString().trim();

			br.close();

		} else {
			System.out.println("Response Code:" + responseCode);
		}

		if (iStream != null) {

			iStream.close();
		}

		if (urlConnection != null) {
			urlConnection.disconnect();
		}
		return data;
	}
	
}
